﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zeus.Thunder.Core;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SharpTrainer.NetWork
{
    class TcpDemoTest : ITestCase
    {
        public void Run()
        {
            new Thread(Server).Start(); // Run server method concurrently.
            Thread.Sleep(2000); // Give server time to start.
            Client();
        }

        static void Client()
        {
            using (TcpClient client = new TcpClient("192.168.1.142", 51111))
            //using (TcpClient client = new TcpClient("localhost", 51111))
            using (NetworkStream n = client.GetStream())
            {
                BinaryWriter w = new BinaryWriter(n);
                Console.WriteLine("Please Input String: ");
                string input = Console.ReadLine();
                w.Write(input);
                w.Flush();
                Console.WriteLine(new BinaryReader(n).ReadString());
            }
        }

        static void Server() // Handles a single client request, then exits.
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 51111);
            listener.Start();

            using (TcpClient c = listener.AcceptTcpClient())
            using (NetworkStream n = c.GetStream())
            {
                string msg = new BinaryReader(n).ReadString();
                BinaryWriter w = new BinaryWriter(n);
                w.Write("Response From Server: You input " + msg + ", right?");
                w.Flush(); // Must call Flush because we're not
            } // disposing the writer.

            listener.Stop();
        }
    }
}
